//
//  RJCheckBottomView.m
//  AirQuality
//
//  Created by Po on 15/3/13.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCheckBottomView.h"
#import "RJCheckBottomCell.h"



#import "RJTools.h"


@interface RJCheckBottomView () <UITableViewDataSource, UITableViewDelegate>

@property (retain, nonatomic) UITableView * tableView;      //城市信息列表

@property (assign, nonatomic) BOOL isNetDown,doRequest,displayBool;               //网络连接结束否

@property (strong, nonatomic) NSString * stationCode;       //城市编号

@property (strong, nonatomic) NSArray * stationData;
@property (strong, nonatomic) NSMutableArray * allStation, * displayRowArray;
@property (strong, nonatomic) NSArray * dataSource;   //所有站点信息
@property (strong, nonatomic) NSMutableArray * classFictionArr;
@property (assign) NSInteger notiCount;

- (void)initData;
- (void)initInterface;
@end

@implementation RJCheckBottomView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initData];
        [self initInterface];
        _notiCount = 0;
    }
    return self;
}

#pragma mark - user-defined initialization function
- (void)initData
{
    _isNetDown = NO;
    _doRequest = YES;
    _displayBool = NO;
    _dataSource = [NSArray array];
    _allStation = [NSMutableArray array];
    _displayRowArray = [NSMutableArray array];
    _model = [[RJCheckBottomModel alloc] init];
    _stationType = [NSMutableArray array];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(positionValueIsGet:) name:@"PositionValueIsGet" object:nil];    
}

- (void)initInterface
{
    [self addSubview:[self getTableView]];
}

- (UITableView *)getTableView
{
    if (!_tableView) {
        CGRect rect = self.bounds;
        _tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        _tableView.contentInset =  UIEdgeInsetsMake(0, 0,50, 0);
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
//        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    }
    return _tableView;
}

#pragma mark - function
- (void)reSetCityStation:(NSArray *)stations cityName:(NSString *)name
{
    _notiCount = 0;
    [_model setSrcData:stations];   
}

- (void)setAirKey:(NSString *)key
{
    _model.keyString = key;
    [_tableView reloadData];
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_delegate) {
        NSDictionary * dic = _model.positionData[indexPath.row];
        NSString * cityName;
        NSString * stationName;
        stationName = dic[@"POSITIONNAME"];
        cityName = dic[@"AREA"];
//        [_delegate didSelectedRow:indexPath.row data:@{@"STATIONCODE":dic[@"STATIONCODE"]} position:[NSString stringWithFormat:@"%@ - %@",cityName,stationName] modol:_model.positionData];
        NSInteger index = [stationName rangeOfString:@"["].location;
        NSString * titleStr = [stationName substringToIndex:index];
         [_delegate didSelectedRow:indexPath.row data:@{@"STATIONCODE":dic[@"STATIONCODE"]} position:[NSString stringWithFormat:@"%@",stationName] modol:_model.positionData];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _classFictionArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RJCheckBottomCell * cell = [RJCheckBottomCell bottomWithTableView:tableView];
     NSDictionary * positionDic = _classFictionArr[indexPath.row];
     NSMutableString * stationName = [[positionDic objectForKey:@"POSITIONNAME"] mutableCopy];
    NSInteger index = [stationName rangeOfString:@"["].location;
    [stationName insertString:[NSString stringWithFormat:@"\n"] atIndex:index];
    cell.position.text = stationName;
    NSDictionary * dic = [NSDictionary dictionary];
    for (NSDictionary * dic_test in _model.allAirData) {
        NSString * city_stationName = dic_test[@"STATIONNAME"];
        NSInteger index = [city_stationName rangeOfString:@"_"].location;
        NSString * stationName_test = [city_stationName substringWithRange:NSMakeRange(index+1, city_stationName.length-index-1)];
        if ([stationName rangeOfString:stationName_test].location != NSNotFound) {
            dic = dic_test;
            break;
        }
    }
    NSString * key =[RJTools getTrueTypeTitlleWithCellKey:_model.keyString];
    NSString * numString = dic ? dic[key] : @"-";
    NSString * Ikey = [NSString stringWithFormat:@"%@%@",@"I",key];
    NSString * InumString = dic ? dic[Ikey]:@"-";
    NSString * minNum = dic ? dic[[NSString stringWithFormat:@"MAX%@",key]] : @"-";
    NSString * maxNum = dic ? dic[[NSString stringWithFormat:@"MIN%@",key]] : @"-";
    NSInteger maxValue,minValue;
    maxValue = [maxNum integerValue] > [minNum integerValue] ? [maxNum integerValue]:[minNum integerValue];
    minValue = [minNum integerValue] < [maxNum integerValue] ? [minNum integerValue]:[maxNum integerValue];
    if ([_model.keyString isEqualToString:@"co"]) {
        [cell.aqiValue setFont:[UIFont systemFontOfSize:16]];
    } else {
        [cell.aqiValue setFont:[UIFont systemFontOfSize:16]];
    }
    if ([numString isEqualToString:@"(null)"]) {
        numString = @"—";
    }
    cell.aqiValue.layer.masksToBounds = YES;
    [cell setDataValue:numString type:_model.keyString backgroundColorWithValur:InumString];
//    [cell.maxNum setText:[NSString stringWithFormat:@"%ld",maxValue]];
    cell.maxValue.text = [NSString stringWithFormat:@"%ld",maxValue];
//    [cell.minNum setText:[NSString stringWithFormat:@"%ld",minValue]];
    cell.minValue.text = [NSString stringWithFormat:@"%ld",minValue];
    return cell;
}

- (void)getLeftData:(NSString *)stationCode{
    
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].stationData data:@{@"stationcode":stationCode,@"timepoint":[RJTools getTimeWithFormat:@"yyyy-MM-dd" time:YesterdayDate]} completeBlock:^(id responseObject) {
        _stationData = responseObject[@"data"];
        [_allStation addObject:_stationData];
//        NSLog(@"%@",)
        }failBlack:^(id response) {
        
    }];
    
}
#pragma mark - notification
- (void)positionValueIsGet:(NSNotification *)data
{
    
//    if (_dataSource.count == 0) {
//        return;
//    }
    _notiCount ++;
    if (_notiCount > 1) {
        return;
    }
    _classFictionArr = [NSMutableArray array];
    _stationType = [NSMutableArray array];
    _dataSource = _model.positionData;
    if ([data.object[@"result"] isEqualToString:@"1"]) {
        if (_delegate) {
            [_delegate updateDownWithData:data.userInfo];
        }
        for (NSDictionary * dic in _dataSource) {
            NSString * stationType = dic[@"STATIONTYPENAME"];
            if ([stationType isEqualToString:@"城市站"]) {
                [_classFictionArr addObject:dic];
            }
        }
        for (NSDictionary * dic in _dataSource) {
            NSString * stationType = dic[@"STATIONTYPENAME"];
            if ([_stationType indexOfObject:stationType] == NSNotFound && ([stationType isEqualToString:@"城市站"] ||[stationType isEqualToString:@"农村站"])) {
                [_stationType addObject:stationType];
            }
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ShowType" object:nil];
        //更新下方站点数据
        [_tableView reloadData];
    } else {
        if (_delegate) {
            [_delegate netRequestBottomFail];
        }
    }
}

- (void)updateBottomTable:(NSString *)stationClassfiction
{
    [_classFictionArr removeAllObjects];
    for (NSDictionary * dic in _dataSource) {
        NSString * stationType = dic[@"STATIONTYPENAME"];
        if ([stationType isEqualToString:stationClassfiction]) {
            [_classFictionArr addObject:dic];
        }
    }
    //更新下方站点数据
    [_tableView reloadData];
    
}

- (void)freeFunc
{
    [_model setShutDownNet:NO];
    [_model freeSelf];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PositionValueIsGet" object:nil];
}


@end
